package com.example.library.service;


import com.example.library.bean.model.Book;
import com.example.library.bean.model.FavoriteOrder;
import com.example.library.bean.model.User;
import com.example.library.bean.response.FailureCause;
import com.example.library.bean.response.FailureResponse;
import com.example.library.bean.response.Response;
import com.example.library.bean.response.SuccessResponse;
import com.example.library.dao.FavoriteOrderRepository;
import com.example.library.dao.UserRepository;
import com.example.library.util.Constant;
import com.example.library.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 注册
     * @param user
     * @return
     */
    public Response register(User user) {
        if(containUser(user.getSno())){
            return new FailureResponse(FailureCause.USER_ALREADY_EXIST);
        }
        user.setSex(Constant.SECRECY);
        userRepository.save(user);
        return new SuccessResponse("注册成功");
    }

    /**
     * 登录
     * @param sno
     * @param password
     * @return
     */
    public Response login(String sno, String password) {
        User userFound = userRepository.findBySnoAndPassword(sno, password);
        if(userFound != null){
            Response response = new SuccessResponse("登录成功");
            response.setResult(userFound);
            return response;
        }else {
            return new FailureResponse(FailureCause.WRONG_PASSWORD);
        }
    }

    /**
     * 是否含有该sno用户
     * @param sno
     * @return
     */
    public boolean containUser(String sno) {
        long count = userRepository.countAllBySno(sno);
        return count > 0;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public Response updateUser(User user) {
        User userReal = userRepository.findByUserId(user.getUserId());
        if(user.getRealName() != null) {
            userReal.setRealName(user.getRealName());
        }
        if(user.getSex() != null) {
            userReal.setSex(user.getSex());
        }
        if(user.getFavor() != null) {
            userReal.setFavor(user.getFavor());
        }
        userRepository.save(userReal);
        Response response = new SuccessResponse("修改成功");
        response.setResult(userReal);
        return response;
    }

}
